import { _decorator, Component, Node, Input } from 'cc';
import { Global } from '../Global';
import { HeroManage } from './HeroManage';
const { ccclass, property } = _decorator;

@ccclass('HandleController')
export class HandleController extends Component {

    @property({ type: HeroManage })
    hero: HeroManage = null

    _mouseHover = {
        up: false,
        down: false,
        left: false,
        right: false
    }

    start() {
        Global.hc = this
        this.addListener()
    }

    update(deltaTime: number) {
        this.moveByState()
    }

    moveByState() {
        if (this._mouseHover.up) {
            this.hero.up()
        } else if (this._mouseHover.down) {
            this.hero.down()
        } else if (this._mouseHover.left) {
            this.hero.left()
        } else if (this._mouseHover.right) {
            this.hero.right()
        }
    }

    addListener() {
        this.node.getChildByName('Up').on(Input.EventType.TOUCH_START, () => {
            this._mouseHover.up = true
        })
        this.node.getChildByName('Up').on(Input.EventType.TOUCH_CANCEL, () => {
            this._mouseHover.up = false
        })
        this.node.getChildByName('Up').on(Input.EventType.TOUCH_END, () => {
            this._mouseHover.up = false
        })

        this.node.getChildByName('Down').on(Input.EventType.TOUCH_START, () => {
            this._mouseHover.down = true
        })
        this.node.getChildByName('Down').on(Input.EventType.TOUCH_CANCEL, () => {
            this._mouseHover.down = false
        })
        this.node.getChildByName('Down').on(Input.EventType.TOUCH_END, () => {
            this._mouseHover.down = false
        })

        this.node.getChildByName('Left').on(Input.EventType.TOUCH_START, () => {
            this._mouseHover.left = true
        })
        this.node.getChildByName('Left').on(Input.EventType.TOUCH_CANCEL, () => {
            this._mouseHover.left = false
        })
        this.node.getChildByName('Left').on(Input.EventType.TOUCH_END, () => {
            this._mouseHover.left = false
        })

        this.node.getChildByName('Right').on(Input.EventType.TOUCH_START, () => {
            this._mouseHover.right = true
        })
        this.node.getChildByName('Right').on(Input.EventType.TOUCH_CANCEL, () => {
            this._mouseHover.right = false
        })
        this.node.getChildByName('Right').on(Input.EventType.TOUCH_END, () => {
            this._mouseHover.right = false
        })
    }

    removeListener() {
        this.node.getChildByName('Up').off(Input.EventType.MOUSE_DOWN)
        this.node.getChildByName('Down').off(Input.EventType.MOUSE_DOWN)
        this.node.getChildByName('Left').off(Input.EventType.MOUSE_DOWN)
        this.node.getChildByName('Right').off(Input.EventType.MOUSE_DOWN)
    }
}

